<template>
  <div class="inputNumber">
    <!-- <input
      autocomplete="off"
      class="inputNumber__input"
      v-model.lazy="currentNumber"
    /> -->
    <input
      autocomplete="off"
      class="inputNumber__input"
      :value="currentNumber"
      @input="handleInput"
    />
    <div class="inputNumber__wrap">
      <button
        class="inputNumber__btn inputNumber__btn-plus"
        @click="setCurrentNumber(1)"
        :disabled="currentNumber >= max"
      >
        +
      </button>
      <button
        class="inputNumber__btn"
        @click="setCurrentNumber(-1)"
        :disabled="currentNumber <= min"
      >
        -
      </button>
    </div>
  </div>
</template>

<script>
import debounce from "lodash/debounce";
export default {
  name: "InputNumber",
  data() {
    return {
      currentNumber: this.value, // 初始值为传的value
    };
  },
  props: {
    min: {
      type: Number,
      default: 1,
    },
    max: {
      type: Number,
      default: 10,
    },
    // 需要外面使用传进来初始值  不一定是1 也有2
    value: {
      type: Number,
      default: 1,
    },
  },
  methods: {
    // 加减操作
    setCurrentNumber(value) {
      this.currentNumber += value;
    },
    // 使用防抖优化input事件
    handleInput: debounce(function (e) {
      this.currentNumber = e.target.value;
    }, 500),
  },
  watch: {
    value(newVal){
      this.currentNumber = newVal // 监视value的改变 一改变需要更新input中的currentNumber
    }, 
    currentNumber(newCurrentNumber, oldCurrentNumber) {
      // console.log(newCurrentNumber,oldCurrentNumber);
      const { min, max } = this;
      let currentNumber = +newCurrentNumber;
      if (currentNumber < min) currentNumber = min; // 小于最小值 要等于最小值
      if (currentNumber > max) currentNumber = max; // 大于最大值 要等于最大值
      if (Number.isNaN(currentNumber)) currentNumber = oldCurrentNumber; // 不是数字 要等于上一个值
      this.currentNumber = currentNumber;
      this.$emit("input", currentNumber); // 发送自定义事件 input 让父组件的数据同步
    },
  },
};
</script>

<style scoped lang="less">
.inputNumber {
  display: flex;
  // color: #333;
}
.inputNumber__input {
  width: 40px;
  height: 40px;
  outline: none;
  text-align: center;
  border: 1px solid #ddd;
}
.inputNumber__wrap {
  display: flex;
  flex-direction: column;
  justify-content: center;
  border: 1px solid #ddd;
  box-sizing: border-box;
  border-left: none;
}
.inputNumber__btn {
  width: 20px;
  height: 20px;
  border: 0;
  font-size: 16px;
  font-weight: 600;
  &:disabled {
    background-color: #fef9f9;
    cursor: not-allowed;
  }
}
.inputNumber__btn-plus {
  border-bottom: 1px solid #ccc;
}
</style>
